package org.bspv.pharma.business.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.bspv.pharma.business.SecurityBusinessService;
import org.bspv.pharma.manager.CredentialManager;
import org.bspv.pharma.manager.UserManager;
import org.bspv.pharma.model.User;
import org.bspv.pharma.model.security.Authority;
import org.bspv.pharma.model.security.Credential;
import org.bspv.pharma.model.security.SecurityUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 
 * @author guillaume
 * 
 */
@Service(value = "securityBusinessService")
public class SecurityBusinessServiceImpl implements SecurityBusinessService {

    /**
     * Service basique de gestion des utilisateurs.
     */
    @Autowired
    private UserManager userManager;
    /**
     * Service basique de gestion des <code>credential</code>.
     */
    @Autowired
    private CredentialManager credentialManager;

    /**
     * @param userManager
     *            the userManager to set
     */
    public void setUserManager(UserManager userManager) {
        this.userManager = userManager;
    }

    /**
     * @param credentialManager
     *            the credentialManager to set
     */
    public void setCredentialManager(CredentialManager credentialManager) {
        this.credentialManager = credentialManager;
    }

    /**
     * {@inheritDoc}
     */
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {

        User user = userManager.getUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException(username + " not found as user");
        }
        SecurityUser pharmaUser = new SecurityUser(user);
        List<Credential> credentials = credentialManager.findValidCredentials(user, new Date());
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        ;
        for (Credential credential : credentials) {
            authorities.add(new Authority(credential.getRole().getLabel()));
        }
        pharmaUser.setAuthorities(authorities);
        return pharmaUser;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public User findUserById(Long id) {
        return userManager.findById(id);
    }
    
    

}
